package com.xgc.book.bookserver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xgc.book.bookserver.bean.UserinfoBean;
import com.xgc.book.bookserver.mapper.UserinfoMapper;
import com.xgc.book.bookserver.service.CodeService;
import com.xgc.book.bookserver.service.TokenService;
import com.xgc.book.bookserver.service.UserinfoService;
import com.xgc.book.bookserver.util.ResultJson;
import com.xgc.book.bookserver.util.exception.RTException;
import com.xgc.book.bookserver.util.form.LoginForm;
import com.xgc.book.bookserver.util.form.PasswordForm;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 用户登录表 服务实现类
 * </p>
 *
 * @author wrz
 * @since 2023-11-20
 */
@Service
@Transactional
public class UserinfoServiceImpl extends ServiceImpl<UserinfoMapper, UserinfoBean> implements UserinfoService {

    @Autowired
    private CodeService codeService;
    @Autowired
    private TokenService tokenService;

    @Value("${admin.default.password}")
    private String defaultPassword;

    @Override
    public ResultJson login(LoginForm loginForm) {
        if (!codeService.checkKaptcha(loginForm.getUuid(), loginForm.getCode())) {
            return ResultJson.error("验证码不正确！");
        }
        loginForm.setPassword(DigestUtils.md5Hex(loginForm.getPassword()));
        UserinfoBean userinfo =
                this.getOne(new QueryWrapper<UserinfoBean>().eq("username", loginForm.getUsername()).eq("password",
                        loginForm.getPassword()));
        if (userinfo == null) {
            return ResultJson.error("用户名或密码不正确！");
        }
        if (userinfo.getStatus() == 2) {
            return ResultJson.error("用户被封禁！");
        }
        return tokenService.saveToken(userinfo.getUserId());
    }

    @Override
    public ResultJson getPage(int page, int limit, UserinfoBean userinfo) {
        IPage<UserinfoBean> iPage = this.page(new Page<>(page, limit),
                new QueryWrapper<UserinfoBean>()
                        .eq(StringUtils.isNotEmpty(userinfo.getUsername()), "username", userinfo.getUsername())
                        .like(StringUtils.isNotEmpty(userinfo.getNickname()), "nickname", userinfo.getNickname())
                        .eq(StringUtils.isNotEmpty(userinfo.getPhone()), "phone", userinfo.getPhone())
                        .eq(userinfo.getRole() != null, "role", userinfo.getRole())
                        .eq(userinfo.getStatus() != null, "status", userinfo.getStatus())
                        .orderByDesc("user_id")
        );
        return ResultJson.ok(iPage);
    }

    @Override
    public void update(UserinfoBean userinfo) {
        if (userinfo.getUserId() == null) {
            UserinfoBean user = this.getOne(new QueryWrapper<UserinfoBean>().eq("username", userinfo.getUsername()));
            if (user != null) {
                throw new RTException("用户名已存在！");
            }
            userinfo.setPassword(DigestUtils.md5Hex(defaultPassword));
            this.save(userinfo);
        } else {
            if (userinfo.getUserId() == 1 && userinfo.getStatus() != null) {
                throw new RTException("管理员状态禁止更改！");
            }
            this.updateById(userinfo);
        }
    }

    @Override
    public void updatePassword(PasswordForm passwordForm) {
        UserinfoBean userinfo = this.getById(passwordForm.getUserId());
        if (userinfo == null) {
            throw new RTException("编号异常！");
        }
        if (!userinfo.getPassword().equals(DigestUtils.md5Hex(passwordForm.getOldPwd()))) {
            throw new RTException("原密码不正确！");
        }
        userinfo = new UserinfoBean();
        userinfo.setUserId(passwordForm.getUserId());
        userinfo.setPassword(DigestUtils.md5Hex(passwordForm.getPassword()));
        this.updateById(userinfo);
    }

    @Override
    public ResultJson getAuthorList() {
        List<UserinfoBean> authorList = this.list(new QueryWrapper<UserinfoBean>().eq("role", 2));
        return ResultJson.ok(authorList);
    }
}
